package primary.others;

import java.util.Stack;

/**
 * @Author Elephas
 * @Date 2022/1/9
 **/
public class IsValid {
    public boolean isValid(String s){
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        boolean flag = true;
        for (int i = 0; i < chars.length; i++) {
            if(chars[i] == '[' || chars[i] == '(' || chars[i] == '{') {
                stack.push(chars[i]);
            }else{
                if(stack.isEmpty()){
                    flag = false;
                    break;
                }
                if(chars[i] == '}'){
                    if(stack.pop() != '{'){
                        flag = false;
                        break;
                    }
                }else if(chars[i] == ')'){
                    if(stack.pop() != '('){
                        flag = false;
                        break;
                    }
                }else if(chars[i] == ']'){
                    if(stack.pop() != '['){
                        flag = false;
                        break;
                    }
                }


            }
        }
        if(!stack.isEmpty())
            flag = false;
        return flag;
    }
}
